//@version=6

indicator("Anax Dynamic Engine [v18.1 LITE + EOD + PHASE]", "Anax Engine V18.1", overlay=true, max_bars_back=5000, max_boxes_count=500, max_labels_count=500, max_lines_count=500, max_polylines_count=100)



// 🚀 UPGRADE: Phantom Rendering Disabled

plot(na, title="[Placeholder]", display=display.none)



//──────────────────────────────────────────────────────────────────────────────

// 1. INPUTS & ENTERPRISE CONFIGURATIONS

//──────────────────────────────────────────────────────────────────────────────

grpCore = "Gemini Core System [v18.1 PRO]"

mode = input.string("Normal", "Processing Mode", options=["Low-Power", "Normal", "Full", "Ultra-Compute"], group=grpCore, tooltip="Ultra-Compute utilizes maximum memory allocation.")

useWindow   = input.bool(true, "Restrict History", group=grpCore, inline="w")

windowBars  = input.int(2500, "Bars", group=grpCore, inline="w", minval=300, maxval=5000)

confirmedOnly = input.bool(false, "Confirmed Signals Only", group=grpCore)



grpV18 = "☢️ V18: Multi-Dimensional Order Flow Engine"

useFootprint = input.bool(true, "🚀 Enable HTF Footprint Gatekeeper", group=grpV18)

ticksPerRow = input.int(10, "Ticks Per Row", group=grpV18)

vaPercent = input.int(70, "Value Area %", group=grpV18)

imbalancePct = input.float(300.0, "Imbalance % Threshold", group=grpV18)



grpEOD = "⏳ End of Day (EOD) Sniper Protocol"

enableEodFilter = input.bool(false, "Enable EOD Gate (Real-Time Alerts)", group=grpEOD, tooltip="Εάν ενεργοποιηθεί, το Alert θα χτυπήσει ζωντανά Χ λεπτά πριν κλείσει το ημερήσιο κερί.")

eodMinutes = input.int(60, "Minutes Before Close to Activate", group=grpEOD)



grpv12 = "🌌 V15/V16 God-Tier Bottoms Protocol"

useLorentz = input.bool(true, "Enable Lorentzian KNN Distance", group=grpv12)

useHurst = input.bool(true, "Enable Hurst Exponent (Market Regime)", group=grpv12)

useBitwise = input.bool(true, "Enable Bitwise State Machine", group=grpv12)

useRLMab = input.bool(true, "Enable MAB Adaptive Z-Score", group=grpv12)



grpv16 = "🧬 V16 Neural Matrix & OFE Tensor"

useHmm = input.bool(true, "Enable HMM Regime Probability", group=grpv16)

useOfe = input.bool(true, "Enable Order Flow Exhaustion (OFE)", group=grpv16)

useDtw = input.bool(true, "Enable Dynamic Time Warping (DTW)", group=grpv16)



grpMacro = "🌐 Cross-Market Confluence (Arbitrage)"

useMacro = input.bool(false, "Enable Macro Asset Confluence", group=grpMacro)

macroTicker = input.symbol("AMEX:SPY", "Macro Asset (e.g. SPY/BTC)", group=grpMacro)



grpHTF = "🌍 HTF Alignment & Kalman Filter"

useHTF       = input.bool(false, "Filter Signals by HTF Trend", group=grpHTF)

htfRes       = input.timeframe("1D", "HTF Timeframe", group=grpHTF)

htfLength    = input.int(50, "HTF Length (Kalman/EMA)", group=grpHTF)

useKalman    = input.bool(true, "🚀 Use Dynamic Kalman Filter", group=grpHTF)



grpSess = "🕒 ICT Sessions (Time Filter)"

useSession   = input.bool(false, "Filter Signals by Session", group=grpSess)

sessNY      = input.session("0800-1200", "NY Session (EST)", group=grpSess)

sessLDN     = input.session("0200-0500", "London Session (EST)", group=grpSess)

showSessBg   = input.bool(false, "Highlight Sessions on Chart", group=grpSess)



grpVWAP = "⚓ Institutional VWAP Filter"

useVwapFilter = input.bool(false, "Filter Trades via Anchor VWAP", group=grpVWAP)

vwapAnchor = input.string("Month", "VWAP Anchor", options=["Session", "Week", "Month"], group=grpVWAP)



grpQuantum = "🎯 Quantum Sniper Engine & Machine Learning"

enableQuantum = input.bool(true, "Enable Quantum Ghost Blocks", group=grpQuantum)

showHeavyOnly = input.bool(true, "💎 Show Heavyweights Only", group=grpQuantum)

volZThreshold = input.float(2.5, "Base Shark Vol Z-Score", group=grpQuantum, step=0.5)

minConfidence = input.float(82.0, "🚀 Min ML Confidence Score (%)", group=grpQuantum, step=1.0)



microTF1      = input.timeframe("2",  "X-Ray TF 1", group=grpQuantum, inline="qTF1")

microTF2      = input.timeframe("4",  "X-Ray TF 2", group=grpQuantum, inline="qTF1")

microTF3      = input.timeframe("10", "X-Ray TF 3", group=grpQuantum, inline="qTF2")

microTF4      = input.timeframe("20", "X-Ray TF 4", group=grpQuantum, inline="qTF2")

microTF5      = input.timeframe("14", "X-Ray TF 5", group=grpQuantum, inline="qTF3")

microTF6      = input.timeframe("28", "X-Ray TF 6", group=grpQuantum, inline="qTF3")



grpGodTier = "⚡ GOD-TIER: Execution & Risk Management"

enableSqueeze = input.bool(true, "Ignite Volatility Squeeze Filter", group=grpGodTier)

enableTP_SL   = input.bool(true, "Draw Dynamic TP/SL Zones", group=grpGodTier)

atrMultSL     = input.float(1.5, "ATR Multiplier for Stop Loss", group=grpGodTier, step=0.1)

enableKelly   = input.bool(true, "Calculate Kelly Criterion %", group=grpGodTier)

enablePOC     = input.bool(true, "Extract LTF Point of Control (POC)", group=grpGodTier)



grpMS = "📐 Structure Intelligence & Liquidity"

showSwing     = input.bool(false, "Show Swing Structure", group=grpMS, inline="s1")

swingLen      = input.int(5, "Len", group=grpMS, inline="s1")

showInternal  = input.bool(false, "Show Internal", group=grpMS, inline="s2")

internalLen   = input.int(3, "Len", group=grpMS, inline="s2")

showDash      = input.bool(true, "Show Dashboard", group=grpMS)

buildSweeps   = input.bool(true, "Mark Liquidity Sweeps (x)", group=grpMS)



grpOB = "🏦 Institutional Blocks (OB)"

showOB         = input.bool(false, "Enable Classic OBs", group=grpOB)

obLast         = input.int(5, "Count", group=grpOB)

obMode         = input.string("Body", "Zone Type", options=["Body","Full"], group=grpOB)

mitiMethod     = input.string("Wick", "Mitigation Trigger", options=["Close","Wick","Avg"], group=grpOB)

hideOverlapOB = input.bool(true, "Cleanup Overlaps", group=grpOB)

obSearchBack  = input.int(80, "Lookback Limit", group=grpOB)



grpFVG = "🧲 Fair Value Gaps (FVG)"

fvgEnable     = input.bool(false, "Enable FVG", group=grpFVG)

fvgLast       = input.int(5, "Count", group=grpFVG)



grpIntel = "🧠 Fusion Intelligence & IOF"

showFusion    = input.bool(true, "Show OB+FVG Confluence (Kill Zones)", group=grpIntel)

enableIOF     = input.bool(true, "🚀 Enable Matrix-based IOF Tracking", group=grpIntel)



//──────────────────────────────────────────────────────────────────────────────

// 1.1 V18.1 LITE GREEN & LITE RED AESTHETICS (BOXES)

//──────────────────────────────────────────────────────────────────────────────

grpAesthetics = "✦ TITAN APEX Aesthetics [v18.1 Lite]"

ghostBullCol  = input.color(color.new(#4ADE80, 92), "Lite Bull (Soft Green)", group=grpAesthetics, inline="c1")

ghostBearCol  = input.color(color.new(#F87171, 92), "Lite Bear (Soft Red)",   group=grpAesthetics, inline="c1")

pocCol        = input.color(color.new(#FFFFFF, 50), "Micro-POC Line", group=grpAesthetics)

tpCol         = input.color(color.new(#4ADE80, 70), "Take Profit Target", group=grpAesthetics)

slCol         = input.color(color.new(#F87171, 70), "Stop Loss Level", group=grpAesthetics)

swingUpCol    = input.color(#4ADE80, "Swing Bull", group=grpAesthetics, inline="s1")

swingDnCol    = input.color(#F87171, "Swing Bear", group=grpAesthetics, inline="s1")

internUpCol   = input.color(color.new(#4ADE80, 60), "Internal Bull", group=grpAesthetics, inline="s2")

internDnCol   = input.color(color.new(#F87171, 60), "Internal Bear", group=grpAesthetics, inline="s2")

obBullCol     = input.color(color.new(#4ADE80, 95), "OB Bull", group=grpAesthetics, inline="ob1")

obBearCol     = input.color(color.new(#F87171, 95), "OB Bear", group=grpAesthetics, inline="ob1")

fvgBullCol    = input.color(color.new(#4ADE80, 96), "FVG Bull", group=grpAesthetics, inline="f1")

fvgBearCol    = input.color(color.new(#F87171, 96), "FVG Bear", group=grpAesthetics, inline="f1")

fusionCol     = input.color(color.new(#A78BFA, 80), "Kill Zone (Purple Glow)", group=grpAesthetics)

dashBg        = input.color(color.new(#0F172A, 92), "Dashboard Background", group=grpAesthetics)



grpAlerts = "🔔 Enterprise Telemetry & Alerts"

enableJsonAlerts = input.bool(true, "Enable JSON Webhook Alerts", group=grpAlerts)

enableUiAlerts   = input.bool(true, "Enable Dynamic UI Alerts", group=grpAlerts)



//──────────────────────────────────────────────────────────────────────────────

// 2. CORE VARIABLES & QUANTITATIVE UPGRADES

//──────────────────────────────────────────────────────────────────────────────

int  obLastEff    = mode == "Low-Power" ? math.min(obLast, 3)  : mode == "Normal" ? obLast : mode == "Full" ? math.min(obLast, 12) : math.min(obLast, 20)

int  fvgLastEff   = mode == "Low-Power" ? math.min(fvgLast, 3) : mode == "Normal" ? fvgLast : mode == "Full" ? math.min(fvgLast, 12) : math.min(fvgLast, 20)

int  ghostLastEff = mode == "Low-Power" ? 10 : mode == "Normal" ? 25 : mode == "Full" ? 50 : 150



grpSafety = "🛡️ Engine Safety & IOF"

force_ha_alerts = input.bool(true, "Force Heikin-Ashi Engine for Alerts", group=grpSafety)

ha_ticker_str = ticker.heikinashi(syminfo.tickerid)

ticker_to_use = force_ha_alerts ? ha_ticker_str : syminfo.tickerid



[backend_ha_o, backend_ha_h, backend_ha_l, backend_ha_c, backend_ha_v] = request.security(ticker_to_use, timeframe.period, [open, high, low, close, volume], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)



float alert_open  = backend_ha_o

float alert_high  = backend_ha_h

float alert_low   = backend_ha_l

float alert_close = backend_ha_c

float alert_vol   = backend_ha_v

float alert_hlc3  = (alert_high + alert_low + alert_close) / 3.0

float current_atr = ta.atr(14)



// ☢️ V18 NATIVE FOOTPRINT INITIALIZATION

footprint reqFootprint = useFootprint ? request.footprint(ticksPerRow, vaPercent, imbalancePct) : na

float fp_delta = useFootprint and not na(reqFootprint) ? reqFootprint.delta() : na

volume_row fp_poc = useFootprint and not na(reqFootprint) ? reqFootprint.poc() : na



float fp_poc_price = na

if useFootprint and not na(fp_poc)

    fp_poc_price := math.avg(fp_poc.up_price(), fp_poc.down_price())



bool htfFpBull = useFootprint and not na(fp_delta) ? fp_delta > 0 : true

bool htfFpBear = useFootprint and not na(fp_delta) ? fp_delta < 0 : true



varip int lastUpdateMs = 0

varip float lastPrice = 0.0

float dynSpatialBoundary = current_atr * 0.1

bool timeGate = (timenow - lastUpdateMs) > 3000

bool spaceGate = math.abs(alert_close - lastPrice) >= math.max(syminfo.mintick * 2, nz(dynSpatialBoundary))



bool isThrottledTick = false

if barstate.isrealtime and not barstate.isconfirmed

    if timeGate and spaceGate

        isThrottledTick := true

        lastUpdateMs := timenow

        lastPrice := alert_close



bool inWindow   = useWindow ? (bar_index > last_bar_index - windowBars) : true

bool isSystemReady = bar_index > 50



bool runComputePhase = confirmedOnly ? barstate.isconfirmed : (barstate.ishistory or barstate.isconfirmed or isThrottledTick)

bool doStep     = runComputePhase and isSystemReady

bool doRender   = barstate.islast



f_hurst(src, len) =>

    float n3 = (ta.highest(src, len) - ta.lowest(src, len)) / (ta.stdev(src, len) + 0.0001)

    math.log(n3) / math.log(len)



float current_hurst = useHurst ? f_hurst(alert_close, 30) : 0.5

bool isMeanReverting = current_hurst < 0.55



f_lorentzian(x1, x2, x3, y1, y2, y3) =>

    math.log(1 + math.abs(x1 - y1)) + math.log(1 + math.abs(x2 - y2)) + math.log(1 + math.abs(x3 - y3))



f_dtw_proxy(val_curr, val_p1, val_p2, val_p3) =>

    float d1 = math.abs(val_curr - val_p1)

    float d2 = math.abs(val_curr - val_p2)

    float d3 = math.abs(val_curr - val_p3)

    math.min(d1, math.min(d2, d3))



f_hmm_state(src, len) =>

    float ret = src - nz(src[1], src)

    float vol = ta.stdev(ret, len)

    float mean_ret = ta.sma(ret, len)

    math.exp(-math.pow(ret - mean_ret, 2) / (2 * math.max(vol, 0.0001)))



var map<string, float> z_score_map = map.new<string, float>()

var int bitwise_state = 0

f_set_bit(int state, int bit_val) => (state % (bit_val * 2)) >= bit_val ? state : state + bit_val



if doStep

    if alert_close > alert_open

        bitwise_state := f_set_bit(bitwise_state, 1)

    else

        bitwise_state := f_set_bit(bitwise_state, 2)

    if isMeanReverting

        bitwise_state := f_set_bit(bitwise_state, 4)



float bb_dev = 2.0 * ta.stdev(alert_close, 20)

float kc_dev = 1.5 * ta.atr(20)

bool isSqueezed = enableSqueeze ? (bb_dev < kc_dev) : false



float volAvg   = ta.sma(alert_vol, 50)

float volStdev = ta.stdev(alert_vol, 50)

float volZ     = (nz(volStdev) > 0) ? (alert_vol - volAvg) / volStdev : 0

var float adaptive_Z = volZThreshold



if barstate.isconfirmed and doStep

    map.put(z_score_map, str.tostring(bar_index), volZ)

    if useRLMab

        float prev_Z = nz(map.get(z_score_map, "Z_OPT"), volZThreshold)

        adaptive_Z := prev_Z * 0.98 + (isSqueezed ? volZThreshold * 1.1 : volZThreshold * 0.9) * 0.02

        map.put(z_score_map, "Z_OPT", adaptive_Z)



f_kalman(src, len) =>

    float estimate = nz(src[1], src)

    float err_measure = ta.stdev(src, len)

    float err_estimate = nz(err_measure[1], err_measure)

    float gain = err_estimate / (err_estimate + err_measure == 0 ? 1 : err_estimate + err_measure)

    estimate + gain * (src - estimate)



[htf_close_raw, htf_ema_raw] = request.security(ticker_to_use, htfRes, [close[1], ta.ema(close[1], htfLength)], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)

float htf_trend_baseline = useKalman ? f_kalman(htf_close_raw, htfLength) : htf_ema_raw



bool isHtfBull_Core = htf_close_raw > htf_trend_baseline

bool isHtfBear_Core = htf_close_raw < htf_trend_baseline

bool isHtfBull = useHTF ? isHtfBull_Core : true

bool isHtfBear = useHTF ? isHtfBear_Core : true

float htf_strength = useHTF ? (math.abs(htf_close_raw - htf_trend_baseline) / htf_trend_baseline) * 100 : 1.0



[macro_c, macro_ema] = request.security(macroTicker, timeframe.period, [close, ta.ema(close, 50)], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)

bool macroBull = useMacro ? macro_c > macro_ema : true

bool macroBear = useMacro ? macro_c < macro_ema : true



bool inNYSess  = time(timeframe.period, sessNY, "America/New_York") != 0

bool inLDNSess = time(timeframe.period, sessLDN, "America/New_York") != 0

bool activeSess = useSession ? (inNYSess or inLDNSess) : true

bgcolor(showSessBg and inNYSess ? color.new(color.blue, 95) : showSessBg and inLDNSess ? color.new(color.orange, 95) : na)



var float vwapValue = na

if useVwapFilter

    vwapValue := ta.vwap(alert_hlc3)

bool vwapBull = useVwapFilter ? (alert_close > vwapValue) : true

bool vwapBear = useVwapFilter ? (alert_close < vwapValue) : true

float vwapDist = useVwapFilter ? math.abs(alert_close - nz(vwapValue)) / nz(vwapValue) * 100 : 0.5



f_bodyLow(int i)  => math.min(alert_open[i], alert_close[i])

f_bodyHigh(int i) => math.max(alert_open[i], alert_close[i])



f_mitiHit(string m, bool bull, float top, float btm, float avg) =>

    bool hit = false

    if bull

        hit := m == "Close" ? f_bodyLow(0) < btm : m == "Wick" ? alert_low < btm : alert_low < avg

    else

        hit := m == "Close" ? f_bodyHigh(0) > top : m == "Wick" ? alert_high > top : alert_high > avg

    hit



f_ml_score(float z, float vDist, float tStr, bool macroConf, float hmmP, bool ofeAct, bool htfOrderFlowConf) =>

    float w_z = 0.45

    float w_v = 0.25

    float w_t = 0.30

    float logit = (z * w_z) - (vDist * w_v) + (tStr * w_t)

    float prob = 100.0 / (1.0 + math.exp(-logit))

    if macroConf

        prob := math.min(100.0, prob + 10.0)

    if useHmm

        prob := math.min(100.0, prob + (hmmP * 10.0))

    if useOfe and ofeAct

        prob := math.min(100.0, prob + 15.0)

    if useFootprint and htfOrderFlowConf

        prob := math.min(100.0, prob + 20.0)

    prob



f_kelly(float winProbPct, float slDist, float tpDist) =>

    float p = winProbPct / 100.0

    float b = tpDist > 0 and slDist > 0 ? tpDist / slDist : 1.0

    math.max(0, (p - ((1.0 - p) / b)) * 100.0)



type Store

    line[]  ln

    label[] lb

    box[]   bx

f_storeNew() => Store.new(array.new_line(), array.new_label(), array.new_box())

f_storeClear(Store st) =>

    if array.size(st.ln) > 0

        for i = 0 to array.size(st.ln) - 1

            line.delete(array.get(st.ln, i))

        array.clear(st.ln)

    if array.size(st.lb) > 0

        for i = 0 to array.size(st.lb) - 1

            label.delete(array.get(st.lb, i))

        array.clear(st.lb)

    if array.size(st.bx) > 0

        for i = 0 to array.size(st.bx) - 1

            box.delete(array.get(st.bx, i))

        array.clear(st.bx)



type OB

    bool  bull

    float top

    float btm

    float avg

    int   t0

    float vol

    bool  isGhost

    bool  isShark

    string tfId

    bool  isPurge

    float confidenceScore

    float pocPrice

    float slPrice

    float tp1Price

    float tp2Price

    float kellyPct

    bool  isSqueezePlay



type FVG

    bool  bull

    float top

    float btm

    float avg

    int   t0



//──────────────────────────────────────────────────────────────────────────────

// 3. MARKET STRUCTURE & LIQUIDITY

//──────────────────────────────────────────────────────────────────────────────

var int   trendSwing = 0

var float lastSh = na

var float lastSl = na

var int   lastShT = na

var int   lastSlT = na

var int   purgeBullTimer = 0

var int   purgeBearTimer = 0

var matrix<float> iofMatrix = enableIOF ? matrix.new<float>(5, 5, 0) : na



float phS = (inWindow and doStep) ? ta.pivothigh(alert_high, swingLen, swingLen) : na

float plS = (inWindow and doStep) ? ta.pivotlow(alert_low, swingLen, swingLen) : na



if not na(phS)

    lastSh := phS

    lastShT := time[swingLen]

    if trendSwing <= 0 and enableIOF and doStep

        matrix.set(iofMatrix, 0, 0, phS)

if not na(plS)

    lastSl := plS

    lastSlT := time[swingLen]

    if trendSwing >= 0 and enableIOF and doStep

        matrix.set(iofMatrix, 1, 0, plS)



var string swingEvent = ""

var float swingEventY = na

var int swingEventT = na

var bool swingSweepUp = false

var bool swingSweepDn = false



swingEvent := ""

swingEventY := na

swingEventT := na

swingSweepUp := false

swingSweepDn := false



if inWindow and doStep

    purgeBullTimer := math.max(0, purgeBullTimer - 1)

    purgeBearTimer := math.max(0, purgeBearTimer - 1)



    if not na(lastSh) and alert_close > lastSh

        swingEvent := (trendSwing <= 0) ? "CHoCH" : "BOS"

        swingEventY := lastSh

        swingEventT := lastShT

        trendSwing := 1

        if enableIOF

            matrix.set(iofMatrix, 2, 0, 1.0)



    if not na(lastSl) and alert_close < lastSl

        swingEvent := (trendSwing >= 0) ? "CHoCH" : "BOS"

        swingEventY := lastSl

        swingEventT := lastSlT

        trendSwing := -1

        if enableIOF

            matrix.set(iofMatrix, 2, 0, -1.0)



    if not na(lastSh) and alert_high > lastSh and alert_close < lastSh

        swingSweepUp := true

        swingEventY := lastSh

        purgeBearTimer := 15



    if not na(lastSl) and alert_low < lastSl and alert_close > lastSl

        swingSweepDn := true

        swingEventY := lastSl

        purgeBullTimer := 15



//──────────────────────────────────────────────────────────────────────────────

// 4. QUANTUM SNIPER ENGINE [v18.1]

//──────────────────────────────────────────────────────────────────────────────

var OB[] ghostBullOB1 = array.new<OB>()

var OB[] ghostBearOB1 = array.new<OB>()

var OB[] ghostBullOB2 = array.new<OB>()

var OB[] ghostBearOB2 = array.new<OB>()

var OB[] ghostBullOB3 = array.new<OB>()

var OB[] ghostBearOB3 = array.new<OB>()

var OB[] ghostBullOB4 = array.new<OB>()

var OB[] ghostBearOB4 = array.new<OB>()

var OB[] ghostBullOB5 = array.new<OB>()

var OB[] ghostBearOB5 = array.new<OB>()

var OB[] ghostBullOB6 = array.new<OB>()

var OB[] ghostBearOB6 = array.new<OB>()



[ltf1_o, ltf1_h, ltf1_l, ltf1_c, ltf1_v] = request.security_lower_tf(ticker_to_use, microTF1, [open, high, low, close, volume])

[ltf2_o, ltf2_h, ltf2_l, ltf2_c, ltf2_v] = request.security_lower_tf(ticker_to_use, microTF2, [open, high, low, close, volume])

[ltf3_o, ltf3_h, ltf3_l, ltf3_c, ltf3_v] = request.security_lower_tf(ticker_to_use, microTF3, [open, high, low, close, volume])

[ltf4_o, ltf4_h, ltf4_l, ltf4_c, ltf4_v] = request.security_lower_tf(ticker_to_use, microTF4, [open, high, low, close, volume])

[ltf5_o, ltf5_h, ltf5_l, ltf5_c, ltf5_v] = request.security_lower_tf(ticker_to_use, microTF5, [open, high, low, close, volume])

[ltf6_o, ltf6_h, ltf6_l, ltf6_c, ltf6_v] = request.security_lower_tf(ticker_to_use, microTF6, [open, high, low, close, volume])



f_scanQuantum(arr_o, arr_h, arr_l, arr_c, arr_v, bullArr, bearArr, string tfLabel) =>

    int sz = array.size(arr_c)

    if sz >= 2 and activeSess

        float avgMicroVol = array.avg(arr_v)

        float stdevMicroVol = array.stdev(arr_v)

        if stdevMicroVol == 0

            stdevMicroVol := 0.0001



        float microPOC = na

        float maxVolNode = 0

        float cumulativeDelta = 0.0



        if enablePOC

            for j = 0 to sz - 1

                float v_t = array.get(arr_v, j)

                float c_t = array.get(arr_c, j)

                float o_t = array.get(arr_o, j)

                if v_t > maxVolNode

                    maxVolNode := v_t

                    microPOC := c_t

                cumulativeDelta += (c_t > o_t ? v_t : c_t < o_t ? -v_t : 0)



        for i = 1 to sz - 1

            float o_prev = array.get(arr_o, i-1)

            float c_prev = array.get(arr_c, i-1)

            float v_prev = array.get(arr_v, i-1)

            float l_prev = array.get(arr_l, i-1)

            float h_prev = array.get(arr_h, i-1)

            float o_curr = array.get(arr_o, i)

            float c_curr = array.get(arr_c, i)

            float l_curr = array.get(arr_l, i)

            float h_curr = array.get(arr_h, i)



            float c_prev2 = i >= 2 ? array.get(arr_c, i-2) : c_prev

            float c_prev3 = i >= 3 ? array.get(arr_c, i-3) : c_prev2

            float v_prev2 = i >= 2 ? array.get(arr_v, i-2) : v_prev



            bool prevRed = c_prev < o_prev

            bool currGrn = c_curr > o_curr

            bool prevGrn = c_prev > o_prev

            bool currRed = c_curr < o_curr



            bool isOfeBull = useOfe ? (prevRed and (v_prev < v_prev2) and math.abs(c_prev - o_prev) < math.abs(c_prev2 - array.get(arr_o, math.max(0, i-2)))) : false

            bool isOfeBear = useOfe ? (prevGrn and (v_prev < v_prev2) and math.abs(c_prev - o_prev) < math.abs(c_prev2 - array.get(arr_o, math.max(0, i-2)))) : false



            float zScore = (v_prev - avgMicroVol) / stdevMicroVol

            bool isVolSpike = zScore > adaptive_Z

            bool isBaseVol  = (v_prev > avgMicroVol * 1.5)



            bool isBullAbsorption = (c_prev < c_curr) and (cumulativeDelta < 0)

            bool isBearAbsorption = (c_prev > c_curr) and (cumulativeDelta > 0)



            float hmmProb = useHmm ? f_hmm_state(c_curr, math.min(10, sz)) : 0.0

            float dtwDist = useDtw ? f_dtw_proxy(c_curr, c_prev, c_prev2, c_prev3) : math.abs(c_curr - c_prev)

            float lorentzDist = useLorentz ? f_lorentzian(c_curr, v_prev, htf_strength, c_prev, avgMicroVol, 1.0) : 0



            float mlScore = f_ml_score(zScore, vwapDist, htf_strength, macroBull, hmmProb, isOfeBull or isOfeBear, (isBullAbsorption and htfFpBull) or (isBearAbsorption and htfFpBear))



            if useLorentz and lorentzDist < 1.5

                mlScore += 5.0

            if useDtw and dtwDist < (current_atr * 0.1)

                mlScore += 5.0

            if isBullAbsorption or isBearAbsorption

                mlScore += 10.0



            if mlScore >= minConfidence

                if isHtfBull and vwapBull and macroBull and prevRed and currGrn and (isVolSpike or isBaseVol)

                    float wickZone = l_curr + ((h_curr - l_curr) * 0.20)

                    if l_prev <= wickZone

                        float sl_val = l_prev - (current_atr * atrMultSL)

                        if useFootprint and not na(fp_poc_price) and fp_poc_price < h_curr and math.abs(h_curr - fp_poc_price) < (current_atr * 1.5)

                            sl_val := fp_poc_price - (syminfo.mintick * 3)



                        float tp1_val = h_curr + (current_atr * 1.5)

                        float tp2_val = h_curr + (current_atr * 3.0)

                        float kelly_v = enableKelly ? f_kelly(mlScore, h_curr - sl_val, tp2_val - h_curr) : 0.0



                        OB gob = OB.new(true, h_curr, l_prev, math.avg(h_curr, l_prev), time, v_prev, true, isVolSpike, tfLabel, purgeBullTimer > 0, mlScore, microPOC, sl_val, tp1_val, tp2_val, kelly_v, isSqueezed)

                        array.unshift(bullArr, gob)



                        if barstate.isconfirmed and i == sz - 1

                            if enableJsonAlerts

                                alert('{"sym": "'+syminfo.ticker+'", "type": "BULL", "price": '+str.tostring(alert_close)+'}', alert.freq_once_per_bar)



                if isHtfBear and vwapBear and macroBear and prevGrn and currRed and (isVolSpike or isBaseVol)

                    float wickZoneTop = h_curr - ((h_curr - l_curr) * 0.20)

                    if h_prev >= wickZoneTop

                        float sl_val = h_prev + (current_atr * atrMultSL)

                        if useFootprint and not na(fp_poc_price) and fp_poc_price > l_curr and math.abs(fp_poc_price - l_curr) < (current_atr * 1.5)

                            sl_val := fp_poc_price + (syminfo.mintick * 3)



                        float tp1_val = l_curr - (current_atr * 1.5)

                        float tp2_val = l_curr - (current_atr * 3.0)

                        float kelly_v = enableKelly ? f_kelly(mlScore, sl_val - l_curr, l_curr - tp2_val) : 0.0



                        OB gob = OB.new(false, h_prev, l_curr, math.avg(h_prev, l_curr), time, v_prev, true, isVolSpike, tfLabel, purgeBearTimer > 0, mlScore, microPOC, sl_val, tp1_val, tp2_val, kelly_v, isSqueezed)

                        array.unshift(bearArr, gob)



                        if barstate.isconfirmed and i == sz - 1

                            if enableJsonAlerts

                                alert('{"sym": "'+syminfo.ticker+'", "type": "BEAR", "price": '+str.tostring(alert_close)+'}', alert.freq_once_per_bar)



        while array.size(bullArr) > ghostLastEff

            array.pop(bullArr)

        while array.size(bearArr) > ghostLastEff

            array.pop(bearArr)



f_cleanGhostOB(arr, isBull) =>

    int sz = array.size(arr) - 1

    while sz >= 0

        if sz < array.size(arr)

            OB g = array.get(arr, sz)

            if (isBull ? alert_close < g.btm : alert_close > g.top)

                array.remove(arr, sz)

        sz -= 1



if enableQuantum and inWindow and doStep

    f_scanQuantum(ltf1_o, ltf1_h, ltf1_l, ltf1_c, ltf1_v, ghostBullOB1, ghostBearOB1, microTF1)

    f_scanQuantum(ltf2_o, ltf2_h, ltf2_l, ltf2_c, ltf2_v, ghostBullOB2, ghostBearOB2, microTF2)

    f_scanQuantum(ltf3_o, ltf3_h, ltf3_l, ltf3_c, ltf3_v, ghostBullOB3, ghostBearOB3, microTF3)

    f_scanQuantum(ltf4_o, ltf4_h, ltf4_l, ltf4_c, ltf4_v, ghostBullOB4, ghostBearOB4, microTF4)

    f_scanQuantum(ltf5_o, ltf5_h, ltf5_l, ltf5_c, ltf5_v, ghostBullOB5, ghostBearOB5, microTF5)

    f_scanQuantum(ltf6_o, ltf6_h, ltf6_l, ltf6_c, ltf6_v, ghostBullOB6, ghostBearOB6, microTF6)

    f_cleanGhostOB(ghostBullOB1, true), f_cleanGhostOB(ghostBearOB1, false)

    f_cleanGhostOB(ghostBullOB2, true), f_cleanGhostOB(ghostBearOB2, false)

    f_cleanGhostOB(ghostBullOB3, true), f_cleanGhostOB(ghostBearOB3, false)

    f_cleanGhostOB(ghostBullOB4, true), f_cleanGhostOB(ghostBearOB4, false)

    f_cleanGhostOB(ghostBullOB5, true), f_cleanGhostOB(ghostBearOB5, false)

    f_cleanGhostOB(ghostBullOB6, true), f_cleanGhostOB(ghostBearOB6, false)



//──────────────────────────────────────────────────────────────────────────────

// 5. CLASSIC OB & FVG ENGINE

//──────────────────────────────────────────────────────────────────────────────

var OB[] bullOB = array.new<OB>()

var OB[] bearOB = array.new<OB>()



f_findLastOppCandle(bool forBull) =>

    int found = na

    int back = math.min(obSearchBack, bar_index)

    if back >= 1

        for i = 1 to back

            if (forBull ? alert_close[i] < alert_open[i] : alert_close[i] > alert_open[i])

                found := i

                break

    found



if inWindow and doStep and swingEvent != ""

    bool bullBreak = (trendSwing == 1)

    int idx = f_findLastOppCandle(bullBreak)

    if not na(idx)

        float top = obMode == "Full" ? alert_high[idx] : f_bodyHigh(idx)

        float btm = obMode == "Full" ? alert_low[idx] : f_bodyLow(idx)

        OB ob = OB.new(bullBreak, top, btm, math.avg(top, btm), time[idx], alert_vol[idx], false, false, "", false, 100.0, na, na, na, na, 0.0, false)

        if (bullBreak and isHtfBull) or (not bullBreak and isHtfBear)

            array.unshift(bullBreak ? bullOB : bearOB, ob)



if inWindow and doStep

    int iB = array.size(bullOB) - 1

    while iB >= 0

        if iB < array.size(bullOB)

            OB z = array.get(bullOB, iB)

            if f_mitiHit(mitiMethod, true, z.top, z.btm, z.avg)

                array.remove(bullOB, iB)

        iB -= 1



    int iS = array.size(bearOB) - 1

    while iS >= 0

        if iS < array.size(bearOB)

            OB z = array.get(bearOB, iS)

            if f_mitiHit(mitiMethod, false, z.top, z.btm, z.avg)

                array.remove(bearOB, iS)

        iS -= 1



var FVG[] bullFVG = array.new<FVG>()

var FVG[] bearFVG = array.new<FVG>()



if inWindow and doStep

    if alert_low > alert_high[2] and isHtfBull

        array.unshift(bullFVG, FVG.new(true, alert_low, alert_high[2], math.avg(alert_low, alert_high[2]), time[2]))

    if alert_high < alert_low[2] and isHtfBear

        array.unshift(bearFVG, FVG.new(false, alert_low[2], alert_high, math.avg(alert_low[2], alert_high), time[2]))



    int jB = array.size(bullFVG) - 1

    while jB >= 0

        if jB < array.size(bullFVG)

            FVG g = array.get(bullFVG, jB)

            if alert_low < g.btm

                array.remove(bullFVG, jB)

        jB -= 1



    int jS = array.size(bearFVG) - 1

    while jS >= 0

        if jS < array.size(bearFVG)

            FVG g = array.get(bearFVG, jS)

            if alert_high > g.top

                array.remove(bearFVG, jS)

        jS -= 1



//──────────────────────────────────────────────────────────────────────────────

// 6. TITAN RENDERING ENGINE [SOLID SIGNALS]

//──────────────────────────────────────────────────────────────────────────────

OB[] renderGhostBull = array.new<OB>()

OB[] renderGhostBear = array.new<OB>()



f_addForRender(arr, targetArr) =>

    int sz = array.size(arr)

    if sz > 0

        for i = 0 to sz - 1

            array.push(targetArr, array.get(arr, i))



if enableQuantum and inWindow

    f_addForRender(ghostBullOB1, renderGhostBull)

    f_addForRender(ghostBullOB2, renderGhostBull)

    f_addForRender(ghostBullOB3, renderGhostBull)

    f_addForRender(ghostBullOB4, renderGhostBull)

    f_addForRender(ghostBullOB5, renderGhostBull)

    f_addForRender(ghostBullOB6, renderGhostBull)



    f_addForRender(ghostBearOB1, renderGhostBear)

    f_addForRender(ghostBearOB2, renderGhostBear)

    f_addForRender(ghostBearOB3, renderGhostBear)

    f_addForRender(ghostBearOB4, renderGhostBear)

    f_addForRender(ghostBearOB5, renderGhostBear)

    f_addForRender(ghostBearOB6, renderGhostBear)



var Store st = f_storeNew()

var table dashboard = table.new(position.top_right, 4, 8, bgcolor=dashBg, frame_color=color.new(#64748B, 60), frame_width=1, border_width=1, border_color=color.new(#64748B, 80))



f_drawOB(OB z, color fillCol, color bbCol) =>

    color boxCol = color.new(fillCol, 94)

    color bordCol = color.new(bbCol, 65)

    array.push(st.bx, box.new(left=z.t0, right=time, top=z.top, bottom=z.btm, xloc=xloc.bar_time, border_color=bordCol, border_width=1, border_style=line.style_solid, bgcolor=boxCol))

    array.push(st.bx, box.new(left=time, right=time + 1, top=z.top, bottom=z.btm, xloc=xloc.bar_time, border_color=na, bgcolor=boxCol, extend=extend.right))



    if z.isGhost

        color sigBgCol = z.bull ? color.new(#10B981, 0) : color.new(#EF4444, 0)

        label.new(x=z.t0, y=z.bull ? z.btm : z.top, xloc=xloc.bar_time, text=(z.isShark ? "🦈" : "⚡") + (z.isPurge ? "🏆" : "") + (z.isSqueezePlay ? "💥" : ""), size=size.tiny, textcolor=color.white, color=sigBgCol, style=z.bull ? label.style_label_up : label.style_label_down)



        if enablePOC and not na(z.pocPrice)

            array.push(st.ln, line.new(x1=z.t0, x2=time, y1=z.pocPrice, y2=z.pocPrice, xloc=xloc.bar_time, color=pocCol, style=line.style_dotted, width=1))

        if enableTP_SL and time == z.t0

            array.push(st.ln, line.new(x1=z.t0, x2=time+10, y1=z.slPrice, y2=z.slPrice, xloc=xloc.bar_time, color=slCol, style=line.style_dashed, width=2))

            array.push(st.ln, line.new(x1=z.t0, x2=time+10, y1=z.tp2Price, y2=z.tp2Price, xloc=xloc.bar_time, color=tpCol, style=line.style_solid, width=2))



if doRender and inWindow

    f_storeClear(st)

    if showSwing and swingEvent != ""

        line.new(x1=swingEventT, x2=time, y1=swingEventY, y2=swingEventY, xloc=xloc.bar_time, color=color.new(trendSwing == 1 ? swingUpCol : swingDnCol, 40), width=1)



    if showOB

        int nB = math.min(obLastEff, array.size(bullOB))

        if nB > 0

            for i = 0 to nB - 1

                f_drawOB(array.get(bullOB, i), obBullCol, obBullCol)



        int nS = math.min(obLastEff, array.size(bearOB))

        if nS > 0

            for i = 0 to nS - 1

                f_drawOB(array.get(bearOB, i), obBearCol, obBearCol)



    if enableQuantum

        int szRenderBull = array.size(renderGhostBull)

        if szRenderBull > 0

            for i = 0 to szRenderBull - 1

                OB z = array.get(renderGhostBull, i)

                if not showHeavyOnly or z.isShark or z.isPurge

                    f_drawOB(z, ghostBullCol, ghostBullCol)



        int szRenderBear = array.size(renderGhostBear)

        if szRenderBear > 0

            for i = 0 to szRenderBear - 1

                OB z = array.get(renderGhostBear, i)

                if not showHeavyOnly or z.isShark or z.isPurge

                    f_drawOB(z, ghostBearCol, ghostBearCol)



    if fvgEnable

        int nfB = math.min(fvgLastEff, array.size(bullFVG))

        if nfB > 0

            for i = 0 to nfB - 1

                FVG g = array.get(bullFVG, i)

                array.push(st.bx, box.new(left=g.t0, right=time, top=g.top, bottom=g.btm, xloc=xloc.bar_time, border_color=na, bgcolor=color.new(fvgBullCol, 96)))



        int nfS = math.min(fvgLastEff, array.size(bearFVG))

        if nfS > 0

            for i = 0 to nfS - 1

                FVG g = array.get(bearFVG, i)

                array.push(st.bx, box.new(left=g.t0, right=time, top=g.top, bottom=g.btm, xloc=xloc.bar_time, border_color=na, bgcolor=color.new(fvgBearCol, 96)))



    if showDash

        table.cell(dashboard, 0, 0, "ANAX ENGINE V18.1", text_color=color.white, bgcolor=color.new(#14B8A6, 30), text_size=size.small)

        table.cell(dashboard, 0, 1, "HTF (Kalman)", text_color=color.new(#94A3B8, 10), text_size=size.small)

        table.cell(dashboard, 1, 1, isHtfBull_Core ? "▲ BULL" : "▼ BEAR", text_color=isHtfBull_Core ? swingUpCol : swingDnCol, bgcolor=color.new(isHtfBull_Core ? swingUpCol : swingDnCol, 90))

        table.cell(dashboard, 0, 2, "Swing Str", text_color=color.new(#94A3B8, 10), text_size=size.small)

        table.cell(dashboard, 1, 2, trendSwing == 1 ? "▲ BULL" : "▼ BEAR", text_color=trendSwing == 1 ? swingUpCol : swingDnCol, bgcolor=color.new(trendSwing == 1 ? swingUpCol : swingDnCol, 90))



        // 🧠 MARKET PHASE DIAGNOSIS [V18.1 UPDATED LABELS]

        string phaseTxt = "CONSOLIDATION ⚖️"

        color phaseCol = color.gray

        color phaseBg = color.new(color.gray, 90)



        if isHtfBull_Core and trendSwing == 1

            phaseTxt := "BULL TREND 🚀"

            phaseCol := swingUpCol

            phaseBg := color.new(swingUpCol, 90)

        else if isHtfBull_Core and trendSwing == -1

            phaseTxt := "PULLBACK 📉"

            phaseCol := color.orange

            phaseBg := color.new(color.orange, 90)

        else if not isHtfBull_Core and trendSwing == -1

            phaseTxt := "BEAR TREND 🩸"

            phaseCol := swingDnCol

            phaseBg := color.new(swingDnCol, 90)

        else if not isHtfBull_Core and trendSwing == 1

            phaseTxt := "FAKE UPTREND 📈"

            phaseCol := color.purple

            phaseBg := color.new(color.purple, 90)



        table.cell(dashboard, 0, 3, "Market Phase", text_color=color.new(#94A3B8, 10), text_size=size.small)

        table.cell(dashboard, 1, 3, phaseTxt, text_color=phaseCol, text_size=size.small, bgcolor=phaseBg)



//──────────────────────────────────────────────────────────────────────────────

// 7. TRADINGVIEW NATIVE ALERT SYSTEM [EOD 1D EDITION]

//──────────────────────────────────────────────────────────────────────────────

f_evalAlert(arr) =>

    bool triggered = false

    if array.size(arr) > 0

        if array.get(arr, 0).t0 == time

            triggered := true

    triggered



// Μηχανισμός One-Shot Real-Time Latch για το EOD Protocol

var int lastEodDay = na

bool isEodTrigger = false



if enableEodFilter and barstate.isrealtime

    int msToClose = time_close("D") - timenow

    if msToClose <= (eodMinutes * 60 * 1000) and msToClose > 0

        if lastEodDay != dayofmonth(timenow)

            isEodTrigger := true

            lastEodDay := dayofmonth(timenow)



bool fireAlertNow = barstate.isconfirmed or isEodTrigger



bool trigAnyBull = false

bool trigAnyBear = false



if fireAlertNow

    trigAnyBull := f_evalAlert(ghostBullOB1) or f_evalAlert(ghostBullOB2) or f_evalAlert(ghostBullOB3) or f_evalAlert(ghostBullOB4) or f_evalAlert(ghostBullOB5) or f_evalAlert(ghostBullOB6)

    trigAnyBear := f_evalAlert(ghostBearOB1) or f_evalAlert(ghostBearOB2) or f_evalAlert(ghostBearOB3) or f_evalAlert(ghostBearOB4) or f_evalAlert(ghostBearOB5) or f_evalAlert(ghostBearOB6)



    if trigAnyBull and enableUiAlerts and isEodTrigger

        alert(syminfo.ticker + " EOD PROTOCOL: GREEN BULL LOCKED", alert.freq_once_per_bar)

    if trigAnyBear and enableUiAlerts and isEodTrigger

        alert(syminfo.ticker + " EOD PROTOCOL: RED BEAR LOCKED", alert.freq_once_per_bar)



alertcondition(trigAnyBull, title="🟢 GREEN BULL Alert", message="Anax Engine: 🟢 BULL TREND Sniper/Shark Detected on {{ticker}}!")

alertcondition(trigAnyBear, title="🔴 RED BEAR Alert", message="Anax Engine: 🔴 BEAR TREND Sniper/Shark Detected on {{ticker}}!")
